<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="../base_path.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">

    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>
    <title>业务模板管理</title>
</head>
<body>
<div class="navbar-fixed-top">
    <div class="breadcrumb">
        <span>系统管理</span>/
        <span class="active">业务模板管理</span>
        <span class="pull-right" title="刷新">
            <div class="btn-refresh" onclick="location.replace(location.href);">
            	<img src="<%=basePath%>/images/refresh.png" >
            </div>
        </span>
    </div>
</div>
<div class="container-fluid">
	<div class="container-fluid-main">
    <div class="page-header">
        <h3>业务模板管理</h3>
		<div class="header-right">
            <button id="btn_create_business_template" type="button" class="btn btn-primary">
                <span class="glyphicon glyphicon-plus"></span> 创建业务模板
            </button>
			 <button id="btn_delete_business_template" type="button" class="btn btn-danger">
			    <span class="glyphicon glyphicon-trash"></span> 删除业务模板
			</button>
		</div>
    </div>
   

    <table id="businessTemplateJQGrid"></table>
    <div style="height: 40px" id="businessTemplateJQGridPager"></div>
	</div>
    <!-- 模态框（Modal） -->
    <div class="modal fade" id="modal_create_business_template" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->


</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/jquery.validate_1.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/messages_zh.js"></script>
<!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>

<script type="text/javascript">
    $(function () {
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
        $("#businessTemplateJQGrid").jqGrid({
            height: 434,
            autowidth: true,
            shrinkToFit: true, /*  autoScroll: false, *//*forceFit: true, */
            colNames: ["主键", "模板名称", "模板编码", "任务地址","备注", "是否已设置语音合成维度","创建时间", "更新时间", "操作人",  "操作"],
            colModel: [
                {name: "template_id", index: "template_id", key: true, hidden: true},
                {name: "template_name", index: "template_name", align: "left", editable: true, editrules: {required:true}},
                {name: "template_code", index: "template_code", align: "left", editable: true, editrules: {required:true}},
                {name: "job_url", index: "job_url", align: "left", editable: true, editrules: {required:false}},
                {name: "template_comment", index: "template_comment", autowidth: true, align: "left", editable: true},
                {name: "bind_tts_config", index: "bind_tts_config", autowidth: true, align: "left"},
				{name: "create_time", index: "create_time", autowidth: true, align: "left"},
                {name: "update_time", index: "update_time", autowidth: true, align: "left"},
                {name: "u_name", index: "u_name", autowidth: true, align: "left"},
                {name: "edit", index: "edit", align: "center", width: 200}
            ],
            pager: "#businessTemplateJQGridPager",
            viewrecords: true,
            hidegrid: false,
            multiselect: true,
            url: "<%=basePath %>/call_config/businessTemplate/getBusinessTemplateDataForJQGrid.do",
            datatype: 'json',
            mtype:"POST",
            rownumbers: true,
            rownumWidth: 100,
            rowNum: 30,
            rowList: [15, 30, 50],
            jsonReader: {
                root: "dataList", page: "currPage", total: "totalPages",          //   很重要 定义了 后台分页参数的名字。
                records: "totalCount", repeatitems: false, id: "template_id"
            },
			subGrid : false,
            loadComplete : function(data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_businessTemplateJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {         // 数据加载完成后 添加 采购按钮
                $("#businessTemplateJQGrid").jqGrid('setLabel', 'rn', '序号', {'text-align': 'center', 'font-size': '12px'}, '');
                var ids = jQuery("#businessTemplateJQGrid").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    var rowData = jQuery("#businessTemplateJQGrid").jqGrid('getRowData', id);
                    var bindTtsConfig = "";
                    if (rowData.bind_tts_config == 0) {
                        bindTtsConfig = "<span class='label label-default'>否</span>";
                    } else {
                        bindTtsConfig = "<span class='label label-primary'>是</span>";
                    }
                    jQuery("#businessTemplateJQGrid").jqGrid('setRowData', ids[i], { bind_tts_config: bindTtsConfig});
                    var editBtn = "<button type='button' class='edit btn btn-link btn-xs' style='margin-right: 10px' onclick='editName(this," + id + ")' >编辑</button>" +
                        "<button type='button' class='save btn btn-link btn-xs hidden' style='margin-right: 10px' onclick='saveName(this," + id + ")'>保存</button>"+
						"<button type='button' class='cancel btn btn-link btn-xs hidden' onclick='cancelName(this," + id + ")' style='margin-right: 2px' >取消</button>";
                    jQuery("#businessTemplateJQGrid").jqGrid('setRowData', ids[i], {edit: editBtn});

                }
            },
            ondblClickRow: function (id) {
            },
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
//                console.log(i);
//                console.log(cm);
                return (cm[i].name != 'edit');
            },
            editurl: "<%=basePath %>/call_config/businessTemplate/templateEdit.do"
        });

        $("#btn_delete_business_template").click(function () {
            var ids = getSelecteds();
            if (ids.length == 0) {
                myNotify("warning", "", "请先选择要删除的业务模板！");
                return;
            }
            bootbox.confirm({
                message: "确认要删除选中的业务模板吗？",
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                    if (result) {
                        displayInfoDelete(ids);
                    }
                }
            });
        });

        $("#btn_create_business_template").click(function () {
            $("#modal_create_business_template").modal({
                remote: '<%=basePath %>/call_config/businessTemplate/showTemplateCreatePage.do'
            });
        });

        $('body').on('hidden.bs.modal', '.modal', function () {
            $(this).removeData('bs.modal');
            refreshJQGrid();
        });
    });

    /******************************方法声明**********************************/

    /**
     * 刷新表格数据
     */
    function refreshJQGrid() {
        $("#businessTemplateJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath %>/call_config/businessTemplate/getBusinessTemplateDataForJQGrid.do",
            mtype: 'POST',
            datatype: "json"
        }).trigger("reloadGrid");
    }
    // 编辑业务模型名称
    function editName(obj, id) {
        $(obj).addClass("hidden");
        $(obj).parent().children(".save").removeClass("hidden");
		 $(obj).parent().children(".cancel").removeClass("hidden");
        $("#businessTemplateJQGrid").jqGrid("editRow", id);
    }
	//取消编辑
	function cancelName(obj, id) {
	    $("#businessTemplateJQGrid").restoreRow(id);
	    $("#businessTemplateJQGrid #" + id).find(".save,.cancel").addClass("hidden");
	    $("#businessTemplateJQGrid #" + id).find(".edit").removeClass("hidden");
	}

    // 保存业务模型名称
    function saveName(obj, id) {
        var name = $("#"+id+'_template_name').val();
        var $val = $.trim($("#"+id+'_job_url').val());
        var code = $.trim($("#"+id+'_template_code').val());
        var check = CheckName(name, true, false, true);
		var note=$.trim($("#"+id+'_template_comment').val());
		var reg = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ,，。._]/g;
        if(!check.pass){
            myNotify("error", "", "模板名称"+check.msg);
            return false;
        }
        if(code == ""){
            myNotify("error", "", "模板编码不能为空，请输入");
            return false;
        }
        if(!(/^[\w\u4e00-\u9fa5]+$/.test( code )&&/^[^_]/.test( code )&&/[^_]$/.test( code ))){
            myNotify("error", "", "模板编码中含有特殊字符，请输入字母数字下划线和汉字且不以下划线开头结尾");
            return false;
        }
        if($val.length > 0 && !/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{0,5})?$/.test($val ) && !/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/.test( $val)){
            myNotify("error", "", "任务地址只支持ip或域名");
            return false;
        }

		if($val.length > 50) {
			myNotify("error", "", "任务地址最大长度50个字符，只支持数字、小数点、冒号");
			return false;
		}

        if(reg.test(note)){
            myNotify("error", "", "字符或格式有误，只支持中文、字母、数字、下划线");
            return false;
        }
		if(note.length>80) {
			myNotify("error", "", "备注最多输入80个字");
			return false;
		}

		if(!checkEditTemplateNameUnique(id, name)) {
			myNotify("error", "", "业务模板名称已存在，请重新输入");
			return false;
		}

        $(obj).addClass("hidden");
        $(obj).parent().children(".edit").removeClass("hidden");
        $("#businessTemplateJQGrid").jqGrid("saveRow", id, onSaveResponse);
    }

    // 处理响应结果
    function onSaveResponse(response) {
        if (response.responseText == "0") {
            myNotify("success", "", "保存成功！");
        } else if (response.responseText == <%=ErrCode.BUSINESS_TEMPLATE_ERR_CODE_INPUT_FOR_MODIFY%>) {
            myNotify("error", "", "输入错误")
        } else if (response.responseText == <%=ErrCode.BUSINESS_TEMPLATE_ERR_CODE_UNIQUENESS%>){
            myNotify("error", "", "名称已存在！");
        } else {
            myNotify("error", "", "保存失败！");
        }
        refreshJQGrid();
    }

    // 执行删除
    function displayInfoDelete(ids) {
        $.ajax({
            url: "<%=basePath%>/call_config/businessTemplate/batchDeleteTemplate.do",
            type: "post",
            async: true,
            data: "ids=" + ids,
            dataType: "json",
            success: function (data) {
                if (data["errorCode"] == "0") {
                    myNotify("success", "", "删除成功！");
                    refreshJQGrid();
                } else {
                    myNotify("error", "", "删除失败！");
                }
            },
            error: function (data) {
                myNotify("error", "", "向服务器发送删除请求过程中发生错误！");
            }
        });
    }

    // 获取选择的行的id，即blacklist_id
    function getSelecteds() {
        //获取多选到的id集合
        var selRows = $("#businessTemplateJQGrid").jqGrid("getGridParam", "selarrrow");
        var ids = [];
        //遍历访问这个集合
        $(selRows).each(function (index, id) {
            //由id获得对应数据行
            var row = $("#businessTemplateJQGrid").jqGrid('getRowData', id);
            ids.push(row.template_id);
        });
        return ids;
    }
    
    function showTtsConfig(templateId) {
        location.href = "<%=basePath%>/call_config/ttsConfig/showTtsConfigInfo.do?templateId=" + templateId;
    }

//验证业务模板名称唯一性
	function checkEditTemplateNameUnique(id, name) {
		var checkEditTemplateNameUrl = "<%=basePath%>/call_config/businessTemplate/checkEditTemplateNameUniqueness.do ";
		var flag;
		$.ajax({
		    url: checkEditTemplateNameUrl,
		    type: "post",
		    async: false,
		    data: {
		        id: id,
				templateName: name
			},
		    dataType: "json",
		    success: function (data) {
		       if(data.errorCode == "0"){
		           flag = true;
		       }else{
		           flag = false;
		       }
		    },
		    error: function (data) {
		        myNotify("error", "", "向服务器发送删除请求过程中发生错误！");
		    }
		});

		return flag
	}
</script>
</body>
</html>